package com.myzl.coal.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.myzl.coal.domain.CommandRecord;
import com.myzl.coal.dto.CmdDTO;
import com.myzl.coal.dto.SendCmdDTO;
import com.myzl.coal.mongo.component.MongoComponent;
import com.myzl.coal.mongo.domain.HistoryData;
import com.myzl.coal.service.ICacheBasicService;
import com.myzl.coal.service.IScaleService;
import com.myzl.coal.service.protocol.CmdService;
import com.myzl.common.core.domain.AjaxResult;
import com.myzl.common.enums.CommandStatusEnum;
import com.myzl.common.enums.DeviceCommandEnum;
import com.myzl.common.enums.DeviceTypeEnum;
import com.myzl.common.enums.PlcWriteEnum;
import com.myzl.common.utils.DateUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author cew
 * @Data 2023年9月27日15:57:33
 */
@Data
@Slf4j
@Service
public class ScaleServiceImpl implements IScaleService {

    private final CmdService cmdService;

    private final MongoComponent mongoComponent;

    private final ICacheBasicService cacheBasicService;

    @Override
    public AjaxResult resetScale(Integer deviceId) {
        SendCmdDTO sendCmdDTO = cmdService.write(new CmdDTO(DeviceTypeEnum.DOUBLE_ORDER.getCode()
                , deviceId, DeviceCommandEnum.RESET_VOLUME.getCode()
                , Collections.singletonList(PlcWriteEnum.ON.getCode())
                , DeviceCommandEnum.RESET_VOLUME.getInfo()));
        CommandRecord commandRecord = mongoComponent.findOneById(sendCmdDTO.getMessageId(), CommandRecord.class);
        if (Objects.equals(commandRecord.getCommandStatus(), CommandStatusEnum.SUCCESS.getCode())) {
            HistoryData lastDensity = null;
            Criteria denistyCriteria = new Criteria();
            denistyCriteria.andOperator(
                    Criteria.where("deviceId").is(deviceId),
                    Criteria.where("dictValue").is(DeviceCommandEnum.CURRENT_DENSITY.getCode())
            );
            Sort sort = Sort.by(Sort.Order.desc("createTime"));
            List<HistoryData> densityList = mongoComponent.selectList(denistyCriteria, 1, sort, HistoryData.class);
            if (densityList.size() > 0){
                lastDensity = densityList.get(0);
                lastDensity.setCreateTime(DateUtils.getNowDate());
                lastDensity.setStartTime(DateUtils.getNowDate());
                lastDensity.setEndTime(null);
            }

            Criteria criteria = new Criteria();
            criteria.andOperator(
                    Criteria.where("deviceId").is(deviceId)
            );
            Long count = mongoComponent.remove(criteria, sort, HistoryData.class);
            if (ObjUtil.isNotNull(lastDensity)){
                mongoComponent.insertOne(lastDensity);
            }
            cacheBasicService.clearCache(deviceId);
            log.info("共删除设备id为{}的数据{}条",deviceId,count);
            return AjaxResult.success();
        }
        return AjaxResult.error("执行失败，请稍后重试");
    }
}
